package com.lianjia.sh.se.esb.server.log;

import com.alibaba.fastjson.JSONObject;
import com.lianjia.sh.se.esb.client.sender.impl.SimpleMessageSender;
import com.lianjia.sh.se.esb.server.log.dao.MessageLogDao;
import com.lianjia.sh.se.esb.server.log.model.MessageLog;
import com.lianjia.sh.se.esb.spi.model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by yangsp1 on 16/7/18.
 */
@Service
public class MessageLogService {
    @Autowired
    SimpleMessageSender messageSender;
    @Autowired
    MessageLogDao messageLogDao;

    /**
     * 插入日志
     * @param message
     */
    @Async
    public void insert(Message message,String actionType,Integer errMaxRepeatCnt){
        Map<String,Object> extendData = message.getExtendData();
        if(extendData == null){
            message.setExtendData(new HashMap<>());
            extendData = message.getExtendData();
        }

        //操作类型
        extendData.put("actionType",actionType);

        //已经重复次数
        Integer errRepeatCnt = (Integer)extendData.get("errRepeatCnt");
        if(errRepeatCnt == null){
            extendData.put("errRepeatCnt",0);
        }

        //最高重复次数
        if(errMaxRepeatCnt == null){
            errMaxRepeatCnt = 0;
        }
        extendData.put("errMaxRepeatCnt",errMaxRepeatCnt);

        MessageLog messageLog = new MessageLog();
        messageLog.setMsgUUId(message.getMsgUUId());
        messageLog.setProjectType(message.getProjectType());
        messageLog.setServiceType(message.getServiceType());
        messageLog.setData(JSONObject.toJSONString(message.getData()));
        if(message.getExtendData() != null) {
            messageLog.setExtendData(JSONObject.toJSONString(message.getExtendData()));
        }
        messageLog.setOperatorEmpNo(message.getOperatorEmpNo());
        messageLog.setOperatorIp(message.getOperatorIp());
        messageLog.setOperateTime(messageLog.getOperateTime());
        messageLogDao.insert(messageLog);
    }
}
